<template>
  <view class="splash">
    <view class="wp">
      <view class="loading">
        <u-loading-icon mode="semicircle" color="#232F3F"></u-loading-icon>
      </view>
      <view class="text">
        <text class="t">{{gStore.token && gStore.openid ? '正在加载中':'正在授权中'}}</text>
      </view>
    </view>
  </view>
</template>
<script setup>
import { globalStore } from "@/store";
const gStore = globalStore();
let callback = gStore.getUrlParam("callback") || "/";
let recNo = gStore.getUrlParam("recNo") || "";
let code = gStore.getUrlParam("code") || "";
const _navigateTo = () => {
  if ((gStore.token && gStore.openid) || gStore.openid) {
    var isSwitchTab =
      callback === "/pages/index/index" ||
      callback === "/" ||
      callback === "/pages/user/index";
    var url = callback === "/" ? "/pages/index/index" : callback;
    if (isSwitchTab) {
      uni.switchTab({
        url: url,
      });
    } else {
      uni.redirectTo({
        url: url,
      });
    }
  }
};
//对后台发送请求传参code获取token和用户信息
const getAuth = (callback) => {
  uni.$request
    .service({
      url: "/wx/auth",
      method: "POST",
      data: {
        code,
        recNo,
      },
    })
    .then((res) => {
      gStore.openid = res.openid;
      gStore.token = res.token;
      callback && callback();
    })
    .catch((err) => {
      if (err.code === 101) {
        window.location.href = uni.$URL + "/pages/index/index";
      }
    });
};
if (code) {
  getAuth(() => {
    _navigateTo();
  });
} else {
  _navigateTo();
}
</script>
<style lang="scss">
.splash {
  display: flex;
  height: 100vh;
  justify-content: center;
  align-items: center;
  .wp {
    display: flex;
    flex-direction: column;
    .loading {
      display: flex;
      justify-content: center;
    }
    .text {
      text-align: center;
      margin-top: 20rpx;
      .t {
        font-size: 28rpx;
        color: #666;
      }
    }
  }
}
</style>
